﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Threading;
using System.Diagnostics;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Interop;
using System.Runtime.InteropServices;

namespace Scarecrow_Network_Manager
{
    /// <summary>
    /// Logica di interazione per App.xaml
    /// </summary>
    public partial class App : Application
    {
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
        [DllImport("user32.dll")]
        static extern bool IsIconic(IntPtr hWnd);
        [DllImport("user32.dll")]
        static extern bool IsZoomed(IntPtr hWnd);

        void App_Startup(object sender, StartupEventArgs e)
        {
            // Application is running
            Process current = Process.GetCurrentProcess();
            Process[] prcs = Process.GetProcessesByName(current.ProcessName);
            if (prcs.Length <= 1)
            {
                // Process command line args
                bool startMinimized = false;
                System.Runtime.Hosting.ActivationArguments args = AppDomain.CurrentDomain.SetupInformation.ActivationArguments;
                if (args != null && args.ActivationData != null)
                {
                    string arg = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData[0];
                    if (!string.IsNullOrWhiteSpace(arg) && arg == "-s")
                    {
                        startMinimized = true;
                    }
                }
                // Create main application window, starting minimized if specified
                //oldMainWindow mainWindow = new oldMainWindow();
                MainWindow mainWindow = new MainWindow();
                if (startMinimized)
                {
                    mainWindow.WindowState = WindowState.Minimized;
                }
                mainWindow.Show();
            }
            else
            {
                foreach (Process process in prcs)
                {
                    if (process.Id != current.Id)
                    {
                        IntPtr hWnd = process.MainWindowHandle;
                        if (hWnd != IntPtr.Zero)
                        {
                            if (IsIconic(hWnd))
                            {
                                ShowWindow(hWnd, 9);
                            }
                            SetForegroundWindow(hWnd);
                        }
                        Application.Current.Shutdown();
                        return;
                    }
                }
            }
        }
    }
}
